package com.thejoyrun.retrofit.http.Interceptor;

import com.thejoyrun.retrofit.http.exception.ServerException;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by kkmike999 on 2016/05/08.
 */
public class ErrorHandleInterceptor implements Interceptor {
	@Override
	public Response intercept(Chain chain) throws IOException {

		Request request = chain.request();

		Response response = chain.proceed(request);

		if (response.isSuccessful() && response.body() != null) {
			// 由于服务器没有返回content-length，所以不能用peekBody()
			MediaType contentType = response.body()
			                                .contentType();
			String content = response.body()
			                         .string();

			checkJsonState(content);

			ResponseBody body = ResponseBody.create(contentType, content);

			return response.newBuilder()
			               .body(body)
			               .build();
		}

		return response;
	}

	private void checkJsonState(String content) {
		try {
			JSONObject json = new JSONObject(content);

			if (json.has("ret")) {
				int ret = json.optInt("ret");

				if (ret == 401) {
					throw new ServerException(ret, "用户在别处登陆");
				}

				if (ret != 0) {
					String msg = json.optString("msg", "");

					throw new ServerException(ret, msg);
				}
			}
		} catch (JSONException e) {
			throw new ServerException(Integer.MIN_VALUE, "返回数据格式有误");
		}
	}
}
